<?php

class Upload
{
    public function __construct(){}

    /**
     * 处理上传文件
     */
    private function dealUpload($updo,$uid=false,$role=1,$filetype='',$size='',$is_admin = false){
        if($is_admin == false){
            if(empty($updo) || ($uid!==false && empty($uid))){
                $error['info'] = 'param is null';
                $error['status'] = 0;
                return $error;
            }
        }else{
            if(empty($updo)){
                $error['info'] = 'param is null';
                $error['status'] = 0;
                return $error;
            }
        }


        if (!empty($_FILES) && $updo != '')
        {
            $do = base64_decode($updo);//还原附件配置别名编码
            $darr = get_attach($do, $uid,$role);//获取附件配置

            $upload = new UploadFile(); // 实例化上传类
            $upload->maxSize = intval($darr['max_size']) * 1024 * 1024;//最大允许上传文件大小

            ////保存规则处理
            if(!in_array($do,array('item_material','material','contract','comments'))){
                $upload->saveRule = 'uniqid';
            }

            $do=='affix' && $upload->saveRule='';

            $upload->savePath = $darr['dir_path']; // 设置附件上传目录,原图片路径
            $upload->uploadReplace = true;

            //设置附件上传类型
            if($filetype){
                $upload->allowExts = explode(',', $filetype);
            }else{
                $upload->allowExts = explode(',', $darr['extension']);
            }

            mk_dir($darr['dir_path'], 0777);//若不存在，则创建文件目录

            if (!$upload->upload())
            {
                //上传错误提示错误信息
                $error['info'] = $upload->getErrorMsg();
                $error['status'] = 0;
                return $error;
            }
            else
            {
                // 上传成功 获取上传文件信息
                $info = $upload->getUploadFileInfo();

                //缩略图尺寸处理
                $thumb = false;
                $prefixArr = array();
                if(!empty($darr['extend']) && strstr($darr['extend'],'*'))
                {
                    $w_h = $this->getWh($darr['extend'],$prefixArr);
                    $thumb = true;
                }

                $filesArr = array();

                foreach($info as $key=>$value){
                    $savename = trim($value['savename'], '.');//保存的文件名
                    $filetype = pathinfo(rtrim($darr['dir_path'],'/').'/'.$savename, PATHINFO_EXTENSION);//获取扩展名，如png,jpg,gif,bmp
                    $is_pic = in_array(strtolower($filetype),array('jpg','jpeg','gif','png','bmp'));

                    //生成相应的缩略图
                    if($thumb && $value['thumb'] && $is_pic){
                        $savename = $this->thumb($do,$w_h,$darr['dir_path'],$savename,$filetype);
                    }


                    $filesArr['files'][$key]['savename'] = $savename;//20140526修改
                    $filesArr['files'][$key]['name'] = trim($info[$key]['name'], '.');//20140526修改
                    $filesArr['files'][$key]['size'] = trim($info[$key]['size'], '.');//20140526修改
                    $filesArr['files'][$key]['type'] = trim($info[$key]['type'], '.');//20140526修改
                    $filesArr['files'][$key]['url'] = trim($darr['img_root'] . $savename, '.');//20140526修改

                    $extend = $darr['extend'];
                    if(empty($extend) || !$is_pic){
                        $filesArr['files'][$key]['smallUrl'] = $filesArr['files'][$key]['bigUrl'] = $filesArr['files'][$key]['midUrl'] = trim($darr['img_root'] . $savename, '.');
                    }else{
                        $filesArr['files'][$key]['bigUrl'] = trim($darr['img_root'] .'1_'. $savename, '.');//20140526修改
                        //中图
                        if(in_array('2_',$prefixArr)){
                            $filesArr['files'][$key]['midUrl'] = trim($darr['img_root'] .'2_'. $savename, '.');//20140526修改
                        } else {
                            $filesArr['files'][$key]['midUrl'] = trim($darr['img_root'] . $savename, '.');//20140526修改
                        }
                        //小图
                        if(in_array('3_',$prefixArr)){
                            $filesArr['files'][$key]['smallUrl'] = trim($darr['img_root'] .'3_'. $savename, '.');//20140526修改
                        } else {
                            $filesArr['files'][$key]['smallUrl'] = trim($darr['img_root'] . $savename, '.');//20140526修改
                        }
                    }
                }
            }
            return array('file'=>$filesArr,'status'=>1);
        }
        else
        {
            $error['info'] = '没有上传文件';
            $error['status'] = 0;
            return $error;
        }
    }

    /**
     * 缩略图处理
     * @param $alias 附件配置别名
     * @param $w_h
     * @param $dir_path
     * @param $savename
     * @param $filetype
     */
    private function thumb($alias,$w_h,$dir_path,$savename,$filetype=''){
        //生成相应的缩略图
        $exif = @exif_read_data(rtrim($dir_path,'/').'/'.$savename);
        if(isset($exif['Orientation'])){
            //数码相机拍照图片处理
            require_once("Lib/WideImage/WideImage.php");
            $image = WideImage::load(rtrim($dir_path,'/').'/'.$savename);
            $image->exifOrient($exif['Orientation'])->saveToFile(rtrim($dir_path,'/').'/'.$savename);
        }

        foreach($w_h as $v){
            if(empty($v['w']) || empty($v['h'])) continue;
            $Image = new ThinkImage(2,rtrim($dir_path,'/').'/'.$savename);

            if(in_array($alias,array('ad'))){
                $thumbType = 1;
            } else {
                $thumbType = 8;
            }
            $Image->thumb($v['w'],$v['h'],$thumbType);
            $thumbName = $v['prefix'].$savename;
            $Image->save(rtrim($dir_path,'/').'/'.$thumbName);
            unset($Image);
        }
        unset($w_h,$dir_path,$exif,$image,$thumbName);

        return $savename;
    }

    private function getWhBySize($size){
        $w_h = array();
        $sizeArr = explode('*', $size);

        $w_h[0]['w'] = $sizeArr[0];
        $w_h[0]['h'] = $sizeArr[1];
        //$prefixArr[] = $w_h[0]['prefix'] = '1_';

        unset($sizeArr);

        return $w_h;
    }

    private function getWh($extend,&$prefixArr=array()){
        $w_h = array();
        $i = 0;
        $extendArr = explode('|',$extend);//标准尺寸
        foreach($extendArr as $val){
            $size = explode('*', $val);
            $w_h[$i]['w'] = $size[0];
            $w_h[$i]['h'] = $size[1];
            $prefixArr[] = $w_h[$i]['prefix'] = ($i+1).'_';
            $i++;
        }

        unset($i,$j,$k,$val,$extendArr);

        return $w_h;
    }

    /**
     * 上传
     * @param $updo
     * @param $uid
     * @param int $returnType
     * @param string $input_field
     * @param string $filetype
     * @return array
     */
    public function upload($updo,$uid,$role=1,$returnType=1,$input_field='',$filetype='',$size='',$is_admin = false)
    {
        $ret = $this->dealUpload($updo,$uid,$role,$filetype,$size,$is_admin);

        if($ret['status']==1){
            $ret['input_field'] = empty($input_field)?'photo':$input_field;
            if($returnType==1){
                $ret['files'] = $ret['file']['files'][0];
            }else{
                $ret['files'] = $ret['file']['files'];
            }
            unset($ret['file']);
        }

        return $ret;
    }

    /**
     * 生成二维码
     * @param $updo
     * @param $uid
     * @param $url
     * @param int $role
     * @return mixed
     */
    public function creadeQrcode($updo,$uid,$url,$role=1){
        $do = base64_decode($updo);
        $darr = get_attach($do,$uid,$role);
        mk_dir($darr['dir_path'], 0777);

        require_once("Lib/phpqrcode/phpqrcode.php");
        $errorCorrectionLevel = 'L';//容错级别
        $matrixPointSize = 4;//生成图片大小

        //生成二维码图片
        $filename = uniqid().'.png';
        $filename_path = $darr['dir_path'].$filename;
        QRcode::png($url, $filename_path, $errorCorrectionLevel, $matrixPointSize, 2);

        $info['status'] = 1;
        $info['info'] = '上传成功';
        $info['file'] = $filename;

        return $info;
    }

    /**
     *根据地址生成图片
     * @param $updo
     * @param $uid
     * @param $location
     * @return mixed
     */
    public function uploadImgForUrl($updo,$uid='',$imgUrl){
        if($updo && $imgUrl){
            $do = base64_decode($updo);//还原附件配置别名编码
            $darr = get_attach($do,$uid);//获取附件配置
            $data = file_get_contents($imgUrl);
            mk_dir($darr['dir_path'], 0777);
            $save_face_name = time().mt_rand().'.png';
            $org_dir = rtrim($darr['dir_path'],'/').'/';
            @file_put_contents($org_dir.$save_face_name,$data);//原图

            $info['status'] = 1;
            $info['info'] = '上传成功';
            $info['file'] = $save_face_name;

            return $info;
        }
    }

    /**
     * 文件重命名
     * @param $alias 附件配置别名
     * @param $uid 用户ID
     * @param $old 原文件名
     * @param $new 修改之后的文件名
     */
    public function rename($alias,$old,$new,$uid=false){
        if(empty($alias) || empty($old) || empty($new)) {
            $info['status'] = 0;
            $info['info'] = '参数错误';
            return $info;
        }

        $darr = get_attach($alias, $uid);

        $dir = rtrim($darr['dir_path'],'/').'/';//路径

        //$new = iconv('UTF-8','GB2312',$new);
        if(IS_WIN){
            $new = iconv('GB2312','UTF-8',$new);
            $old = iconv('UTF-8','GB2312',$old);
        }

        $res = @rename($dir.$old,$dir.$new);//重命名
        @rename($dir.'1_'.$old,$dir.'1_'.$new);//重命名
        @rename($dir.'2_'.$old,$dir.'2_'.$new);//重命名
        @rename($dir.'3_'.$old,$dir.'3_'.$new);//重命名

        if($res){
            return array('status'=>1,'info'=>'ok');
        } else {
            return array('status'=>0,'info'=>'重命名失败');
        }
    }

    /**
     * 文件移动
     * @param $updo
     * @param $origin_uid
     * @param $new_uid
     * @param $filename
     */
    public function move($updo,$origin_uid,$new_uid,$filename){
        $do = base64_decode($updo);
        $this->_move($do,$origin_uid,$new_uid,$filename);
    }

    /**
     * 批量移动
     * @param $moveArr
     */
    public function moveByMuiti($moveArr){
        foreach($moveArr as $val){
            $this->_move($val['alias'],$val['origin_uid'],$val['new_uid'],$val['filename']);
        }
    }

    private function _move($do,$origin_uid,$new_uid,$filename){
        $darr_orgin = get_attach($do, $origin_uid);
        $darr_new = get_attach($do, $new_uid);

        $dir_origin = rtrim($darr_orgin['dir_path'],'/').'/';//路径
        $dir_new = rtrim($darr_new['dir_path'],'/').'/';//路径

        $res = @rename($dir_origin.$filename,$dir_new.$filename);

        if($res){
            return array('status'=>1,'info'=>'ok');
        } else {
            return array('status'=>0,'info'=>'重命名失败');
        }
    }


    /**
     * 重新生成缩略图
     * @param $alias
     * @param $imgArr
     */
    public function regenerate($alias,$imgArr,$role=1,$sizeArr=false){
        if(empty($alias) || empty($imgArr)) return false;

        $i = 0;
        foreach($imgArr as $uid=>$arr){
            $darr = get_attach($alias, $uid,$role);
            if(empty($darr)) continue;
            $size = $sizeArr ? $sizeArr[$i] : false;

            foreach($arr as $arr2){
                foreach($arr2 as $img){
                    if(empty($img)){
                        continue;
                    }
                    $filetype = pathinfo(rtrim($darr['dir_path'],'/').'/'.$img, PATHINFO_EXTENSION);//获取扩展名，如png,jpg,gif,bmp

                    if(!file_exists(rtrim($darr['dir_path'],'/').'/'.$img)){
                        if($filetype=='jpg'){
                            $img = rtrim($img,$filetype).'png';
                        }
                        if(!file_exists(rtrim($darr['dir_path'],'/').'/'.$img)){
                            echo $uid.trim($darr['dir_path'],'/').'/'.$img."  ____ \r\n";
                            continue;
                        }
                    }

                    $thumb = false;
                    if(!empty($darr['extend']) && strstr($darr['extend'],'*'))
                    {

                        $w_h = $this->getWh($darr['extend']);
                        $thumb = true;
                    } else if($size){
                        $w_h = $this->getWhBySize($size);
                        $thumb = true;
                    }

                    if($thumb){
                        //删除原来的缩略图
                        @unlink(rtrim($darr['dir_path'],'/').'/big_'.$img);//删除原来的大图片
                        @unlink(rtrim($darr['dir_path'],'/').'/mid_'.$img);//删除原来的中图片
                        @unlink(rtrim($darr['dir_path'],'/').'/small_'.$img);//删除原来的小图片

                        foreach($w_h as $v)
                        {
                            $thumbName = $v['prefix'].$img;
                            @unlink(rtrim($darr['dir_path'],'/').'/'.$thumbName);//删除原来的图片
                        }

                        //生成相应缩略图
                        $this->thumb($alias,$w_h,$darr['dir_path'],$img,$filetype);
                        //file_put_contents('img.txt',$img,FILE_APPEND);
                    } else {
                        continue;
                    }
                    sleep(5);
                }

            }
            $i++;
        }
        unset($thumb,$thumbName,$w_h,$darr,$img,$filetype,$imgArr,$uid,$arr,$role,$arr2,$i);

        return array('info'=>'success','status'=>1);
    }

    public function upload_face($updo,$uid,$photo,$imgdeg,$w,$h,$x,$y,$callback=''){
        $do = base64_decode($updo);
        if(strpos($photo,'data:image')!==false){
            if(strpos($photo,'data:image/jpeg;base64,')!==false){
                $image_stream = base64_decode(str_replace('data:image/jpeg;base64,','', $photo));
                $extension = '.jpg';
            }elseif((strpos($photo,'data:image/png;base64,')!==false)){
                $image_stream = base64_decode(str_replace('data:image/png;base64,','', $photo));
                $extension = '.png';
            }elseif((strpos($photo,'data:image/gif;base64,')!==false)){
                $image_stream = base64_decode(str_replace('data:image/gif;base64,','', $photo));
                $extension = '.gif';
            }
            if(empty($extension)){
                return array('status'=>0,'info'=>'图片格式错误');
            }

            $darr = get_attach($do, $uid);
            mk_dir($darr['dir_path'], 0777);
            $save_face_name = uniqid().$extension;
            $org_dir = $darr['dir_path'].'/';
            @file_put_contents($org_dir.'temp_'.$save_face_name,$image_stream);//原图，稍后会删除

            cache('db_attach_dir'.$uid,NULL);
        } else {
            $darr = get_attach($do, $uid);
            $save_face_name = end(explode('/',$photo));
            $org_dir = $darr['dir_path'].'/';
            if(!file_exists($org_dir.$save_face_name) || empty($save_face_name)){
                return array('status'=>0,'info'=>'图片不存在或者该图片不允许上传，非法操作');
            }
        }

        // 上传成功 获取上传文件信息
        $info['status'] = 1;
        $info['info'] = '上传成功';
        $info['data'] = $save_face_name;
        $info['path'] = rtrim($darr['img_root'],'/').'/'.$save_face_name;


        $Image = new ThinkImage(2,$org_dir.'temp_'.$save_face_name);
        $Image->rotate($imgdeg);
        $Image->crop($w,$h,$x,$y);
        $Image->save($org_dir.$save_face_name);//真正需要的原图


        //缩略图尺寸处理
        if(!empty($darr['extend']) && strstr($darr['extend'],'*')){
            $sizeArr = explode('|', $darr['extend']);
            $sizeName[0] = 'big_';
            $sizeName[1] = 'mid_';
            $sizeName[2] = 'small_';

            $i=0;
            foreach($sizeArr as $val){
                $size = explode('*', $val);
                $w_h[$i]['w'] = $size[0];
                $w_h[$i]['h'] = $size[1];
                $w_h[$i]['prefix'] = $sizeName[$i];
                $i++;
            }

            $Image = new ThinkImage(2,$org_dir.$save_face_name);
            foreach($w_h as $v){
                $Image->thumb($v['w'],$v['h']);
                $Image->save($org_dir.$v['prefix'].$save_face_name);
                $info[0][$v['prefix'].'file'] = $v['prefix'].$save_face_name;
            }
        }
        unlink($org_dir.'temp_'.$save_face_name);//删除缓存图片
        return $info;
    }

    /**
     * @param array $picArray
     * 下载远程文件
     */
    public function upload_remote($updo,$uid,$picArray)
    {
        $filenameArr = array();

        $do = base64_decode($updo);
        $darr = get_attach($do, $uid);
        $path = $darr['dir_path'];

        //生成相应的缩略图
        $thumb = false;
        if(!empty($darr['extend']) && strstr($darr['extend'],'*'))
        {
            $w_h = $this->getWh($darr['extend']);
            $thumb = true;
        }

        foreach($picArray as $v)
        {
            $index = mb_strrpos($v,'.');
            $extension = strtolower(substr($v,$index));


            $extensionArr = explode(',',$darr['extension']);

            if(!in_array(substr($extension,1),$extensionArr)){
                $extension = '.jpg';
            }

            $time = uniqid();
            $filename = $time.$extension;

            Http::curlDownload($v,rtrim($path,'/').'/'.$filename);

            //生成相应的缩略图
            $filetype = pathinfo(rtrim($darr['dir_path'],'/').'/'.$filename, PATHINFO_EXTENSION);//获取扩展名，如png,jpg,gif,bmp
            $is_pic = in_array(strtolower($filetype),array('jpg','jpeg','gif','png','bmp'));
            if($thumb && $is_pic){
                $filename = $this->thumb($do,$w_h,$darr['dir_path'],$filename,$filetype);
            }

            $filenameArr[] = $filename;
        }

        return array('status'=>1,'file'=>$filenameArr);
    }

    /**
     * 上传资源
     * @param $alias
     * @param $uid
     * @param $media
     * @return bool
     */
    public function uploadReason($alias,$uid,$media){
        if(empty($alias) || empty($uid) || empty($media)) return false;

        $chat = new WeiXin(C('APPID'),C('APPSECRET'));
        $do = base64_decode($alias);//还原附件配置别名编码
        $darr = get_attach($do,$uid);//获取附件配置
        mk_dir($darr['dir_path'], 0777);

        $org_dir = rtrim($darr['dir_path'],'/').'/';
        $fileName = $chat->download_media($media,$org_dir);
        $info['status'] = 1;
        $info['info'] = '上传成功';
        $info['file'] = $fileName;
        return $info;
    }
}